package com.sxz.sbs.module.home;

import android.app.usage.UsageEvents;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sxz.sbs.R;
import com.sxz.sbs.app.App;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.banner.AutoSlipBanner;
import com.sxz.sbs.applibrary.banner.AutoSlippingViewPager;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.data.Params;
import com.sxz.sbs.entity.UploadAppBean;
import com.sxz.sbs.event.AgainLoginEvent;
import com.sxz.sbs.event.JPushRouseEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.home.adapter.HomeAdapter;
import com.sxz.sbs.module.home.bean.HomeBean;
import com.sxz.sbs.module.home.bean.WeatherBean;
import com.sxz.sbs.module.home.presenter.HomePresenter;
import com.sxz.sbs.module.home.view.HomeView;
import com.sxz.sbs.module.mine.PersonageActivity;
import com.sxz.sbs.module.telephone.TelBookActivity;
import com.sxz.sbs.module.update.UploadAppFragment;
import com.sxz.sbs.module.web.WebViewActivity;
import com.sxz.sbs.util.OkGoUpdateHttpUtil;
import com.sxz.sbs.util.VersionUtils;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * @author hp
 * @date 2018/1/5
 * 主页界面
 */

public class HomeActivity extends BaseActivity<HomePresenter> implements SwipeRefreshLayout.OnRefreshListener, HomeView {

    @BindView(R.id.tv_nav_title)
    TextView tvTitle;
    @BindView(R.id.vp_home)
    AutoSlippingViewPager vpHome;

    @BindView(R.id.home_banner)
    MZBannerView homeBanner;

    @BindView(R.id.home_state)
    StateLayout stateLayout;

    @BindView(R.id.rv_home)
    RecyclerView rvHome;
    @BindView(R.id.srl_home)
    SwipeRefreshLayout srlHome;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_weather)
    TextView tvWeather;
    private HomeAdapter homeAdapter;
    private List<HomeBean.AuthListBean> dataList = new ArrayList<>();
    final List<Object> list = new ArrayList<>();
    final List<String> banner_list = new ArrayList<>();
    private LocationClient mLocationClient = null;
    private LocationListener mLocationListener = null;
    private String weatherUrl = null;
    public static boolean isForeground = false;
    private String city;
    String version = "";
    private boolean isList = true;
    boolean isDark = true;
    private UploadAppBean uploadAppBean = null;
    private UploadAppFragment uploadAppFragment = null;
    private MZHolderCreator<BannerViewHolder> mzHolderCreator = new MZHolderCreator<BannerViewHolder>() {
        @Override
        public BannerViewHolder createViewHolder() {
            return new BannerViewHolder();
        }
    };

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        try {
            PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0);
            version = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            version = "1.0";
        }
        sendUpdate();
        if (!App.preferences.getBooleanValue(AppConstant.Preference.JPUSH_SET_RESULT, false)) {
            JPushInterface.setAlias(this, App.preferences.getValue(AppConstant.Preference.USER_NAME), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    if (i == 0) {
                        App.preferences.setBooleanValue(AppConstant.Preference.JPUSH_SET_RESULT, true);
                        //极光设置别名成功
                        LogUtils.i("极光推送", "极光设置别名成功");
                    }
                }
            });
        }
        if (AppConstant.isDebug) {
            tvTitle.setText(R.string.app_name_debug);
        } else {
            tvTitle.setText(R.string.app_name);
        }

        srlHome.setColorSchemeResources(R.color.color_main);

        AutoSlipBanner.configBanner(vpHome, list);
        homeBanner.setPages(banner_list, mzHolderCreator);
        requestLocation();
        rvHome.setLayoutManager(new GridLayoutManager(this, 2));
        rvHome.setNestedScrollingEnabled(false);
        srlHome.setOnRefreshListener(this);
        //  发起请求
        getHomeData();
        homeAdapter = new HomeAdapter(dataList);
        rvHome.setAdapter(homeAdapter);
        rvHome.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtils.i(dataList.get(position).getUrl_ClickUrl(), dataList.get(position).getId());
                ARouter.getInstance()
                        .build(dataList.get(position).getUrl_ClickUrl())
                        .withInt("id", dataList.get(position).getId())
                        .navigation();
            }
        });

        vpHome.setOnPageItemClickListener(new AutoSlippingViewPager.OnPageItemClickListener() {
            @Override
            public void onItemClicked(int index) {
                if (index > list.size()) {
                    return;
                }
                //  startActivity(OrderDetailActivity.class);
                /*if (isDark) {
                    QMUIStatusBarHelper.setStatusBarLightMode(HomeActivity.this);
                } else {
                    QMUIStatusBarHelper.setStatusBarDarkMode(HomeActivity.this);
                }
                isDark = !isDark;*/
                // ToastUtils.showShort(index + "");

            }
        });

        stateLayout.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                srlHome.setRefreshing(true);
                getHomeData();
                if (!TextUtils.isEmpty(city)) {
                    getWeather(city);
                }
            }
        });
    }

    /**
     * 请求定位
     */
    private void requestLocation() {
        mLocationClient = new LocationClient(this, locationOption());
        mLocationListener = new LocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        if ((ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_COARSE_LOCATION")) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.ACCESS_COARSE_LOCATION"}, 66);
        } else {
            mLocationClient.start();
            mLocationClient.requestLocation();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @OnClick({R.id.iv_title_home_tel, R.id.iv_title_home_me, R.id.rl_weather})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_home_tel:
                startActivity(TelBookActivity.class);
                break;
            case R.id.iv_title_home_me:
                startActivity(PersonageActivity.class);
                break;
            case R.id.rl_weather:
                startActivity(new Intent(this, WebViewActivity.class)
                        .putExtra(IntentConstant.WEB_VIEW_URL, weatherUrl));
                break;
            default:
                break;
        }
    }


    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        //  发起请求
        getHomeData();
    }

    /**
     * 获取天气
     */
    public void getWeather(String city) {
        isList = false;
        HashMap<String, Object> map = new HashMap<>();
        map.put("city", city);
        mPresenter.getWeatherData(map);
    }

    private void getHomeData() {
        isList = true;
        mPresenter.getHomeData(HttpParamMap.getParamMap());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onJPushRouseEvent(JPushRouseEvent event) {
        getHomeData();

        if (!TextUtils.isEmpty(city)) {
            getWeather(city);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAgainLoginEvent(AgainLoginEvent event) {
        getHomeData();
        if (!TextUtils.isEmpty(city)) {
            getWeather(city);
        }
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        homeBanner.start();

        //  发起请求
        /*mPresenter.getHomeData(HttpParamMap.getParamMap());
        if (!TextUtils.isEmpty(city)) {
            getWeather(city);
        }*/
    }

    @Override
    protected void onPause() {
        super.onPause();
        homeBanner.pause();
    }

    @Override
    protected void onDestroy() {
        isForeground = false;
        if (vpHome != null) {
            vpHome.stopAutoSlipping();
        }
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient.stop();
            mLocationClient = null;
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    /**
     * 定位回调
     */
    private class LocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null) {
                tvLocation.setText("郑州");
                city = "郑州";
                getWeather("郑州");
                return;
            }
            if (TextUtils.isEmpty(bdLocation.getCity())) {
                Params.currentCity = "郑州";
                tvLocation.setText("郑州");
                getWeather("郑州");
                city = "郑州";
            } else {
                Params.currentCity = bdLocation.getCity();
                tvLocation.setText(bdLocation.getDistrict());
                getWeather(bdLocation.getCity().endsWith("市") ? bdLocation.getCity().substring(0, bdLocation.getCity().length() - 1) : bdLocation.getCity());
                city = bdLocation.getCity().endsWith("市") ? bdLocation.getCity().substring(0, bdLocation.getCity().length() - 1) : bdLocation.getCity();
            }

        }
    }

    /**
     * 权限申请结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 66) {
            if (grantResults != null) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationClient.start();
                    mLocationClient.requestLocation();
                } else {
                    mLocationClient.stop();
                    tvLocation.setText("郑州");
                    getWeather("郑州");
                }
            }
        }
    }

    @Override
    public void onGetHomeDataSuccess(HomeBean data) {
        if (mIsLive && data != null) {
            srlHome.setRefreshing(false);
            List<HomeBean.BannerListBean> bannerList = data.getBannerList();
            list.clear();
            for (int i = 0; i < bannerList.size(); i++) {
                list.add(bannerList.get(i).getUrl_ImageUrl());
                banner_list.add(bannerList.get(i).getUrl_ImageUrl());
            }
            LogUtils.i("vpHome list is ", list.toString());
            AutoSlipBanner.configBanner(vpHome, list);

            homeBanner.setPages(banner_list, mzHolderCreator);
            stateLayout.showContent();
            dataList.clear();
            dataList.addAll(data.getAuthList());
            LogUtils.i("dataList is ", dataList.toString());
            homeAdapter.notifyDataSetChanged();

        }
    }

    @Override
    public void onGetWeatherDataSuccess(WeatherBean data) {
        if (mIsLive && data != null) {
            tvWeather.setText(data.getWeather().getText() + " " + data.getWeather().getTemperature() + "℃");
            weatherUrl = data.getUrl();
        }
    }

    @Override
    public void onGetVersionSuccess(UploadAppBean data) {
        if (data != null) {
            uploadAppBean = data;
            if (VersionUtils.compareVersion(data.getVersion(), version) > 0) {
                uploadAppFragment = UploadAppFragment.newInstance(data);
                uploadAppFragment.showDialog(getSupportFragmentManager());
            }
        }
    }

    @Override
    public void loginAgain() {
        super.loginAgain();
        if (srlHome != null) {
            srlHome.setRefreshing(false);
        }
    }

    @Override
    public void showError(int errorTag, String msg) {
        if (srlHome != null) {
            srlHome.setRefreshing(false);
        }
        if (isList) {
            if (errorTag == AppConstant.NET_ERROR_CODE) {
                stateLayout.showNetwork();
            } else {
                stateLayout.showError();
            }
        } else {
            super.showError(errorTag, msg);
        }


    }

    /**
     * 设置定位参数
     *
     * @return
     */
    public LocationClientOption locationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(false);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        return option;
    }

    /**
     * 在线更新
     */
    private void sendUpdate() {
       /* HashMap<String,Object> map = HttpParamMap.getParamMap();
        map.put("type",1);
        mPresenter.getVersion(map);*/
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<String, String>();
        params.put("type", "1");
        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(AppConstant.BASE_URL + AppConstant.HOST_URL + "/login/getAppVersion")
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                .setTopPic(R.drawable.top_3)
                .setThemeColor(0xff00CAA3)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {

                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject object = new JSONObject(json);
                            JSONObject jsonObject = object.getJSONObject("model");
                            String isUpdate = "No";

                            if (VersionUtils.compareVersion(jsonObject.optString("Version"), version) > 0) {
                                isUpdate = "Yes";
                            }
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate(isUpdate)
                                    //（必须）新版本号，
                                    .setNewVersion(jsonObject.optString("Version"))
                                    //（必须）下载地址
                                    .setApkFileUrl(jsonObject.optString("URL"))
                                    //（必须）更新内容
                                    .setUpdateLog(jsonObject.optString("Content"))
                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize(jsonObject.optString("Size"))
                                    //是否强制更新，可以不设置
                                    .setConstraint(jsonObject.optInt("IsForce") == 1 ? true : false)
                            ;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    @Override
                    public void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        //ToastUtils.showShort("sad ");
                        try {
                            updateAppManager.showDialogFragment();
                        } catch (Exception e) {
                            LogUtils.e(e.getMessage());
                        }

                        //自定义对话框
                        //showDiyDialog(updateApp, updateAppManager);
                    }

                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 666 && uploadAppBean != null) {
            if (uploadAppBean.getIsForce() != 1 &&
                    !uploadAppBean.getVersion().equals(AppUtils.getAppVersionName())) {
                if (uploadAppFragment != null) {
                    uploadAppFragment.dismiss();
                }
            }
        }
    }

    public static class BannerViewHolder implements MZViewHolder<String> {

        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.item_banner, null);
            mImageView = view.findViewById(R.id.banner_image);
            mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return view;
        }

        @Override
        public void onBind(Context context, int i, String s) {
            RequestOptions requestOptions = new RequestOptions()
                    .placeholder(R.drawable.img_banner)
                    .error(R.drawable.img_banner);
            Glide.with(context)
                    .load(s)
                    .apply(requestOptions)
                    .into(mImageView);
        }


    }


    /**
     * 退出时的时间
     */
    private long mExitTime;

    /**
     * 对返回键进行监听
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ToastUtils.showShort("再按一次退出百年利人！");
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }
}
